<?php
// +----------------------------------------------------------------------
// |地址管理
// +----------------------------------------------------------------------
// |Data:2016-06-25 18:46
// +----------------------------------------------------------------------
// |Author: 吕志雄 <870923001@qq.com>
// +----------------------------------------------------------------------
namespace Wap\Model;
use Common\Model\CommonModel;

class AddressModel extends CommonModel{
    protected $tableName = 'user_address';
    private $sp_user_address_detail_cache_key = 'sp_user_address_detail_';
    private $sp_user_address_list_cache_key = 'sp_user_address_list_';

    public function getAll($map = array(), $order = ''){
        $list = S($this->sp_user_address_list_cache_key.$map['uid']);
        if(!$list){
            $list = $this->where($map)->order($order)->select();
            S($this->sp_user_address_list_cache_key.$map['uid'],$list);
        }
        return $list;
    }

    public function detail($id, $field = true){
        $detail =  S($this->sp_user_address_detail_cache_key.$id);
        if(!$detail){
            $detail = parent::detail($id, $field);
            S($this->sp_user_address_detail_cache_key.$id,$detail);
        }
        return $detail;
    }

    public function update($data, $id = null){
        $result = parent::update($data, $id);
        if($result){
            $this->clearCache($data['id'],$data['uid']);
        }
        $id = $data['id'] ? $data['id'] : $result;
        return $id;
    }

    public function del($id,$uid){
        $result = parent::del($id);
        if($result){
            $this->clearCache($id,$uid);
        }
        return $result;
    }

    /**
     * 获取常用的地址
     * @param $uid
     * @return bool
     */
    public function getUseAddress($uid){
        if(empty($uid)) return false;
        $detail = $this->where('uid='.$uid)->order('use_time desc')->find();
        return $detail;
    }

    public function clearCache($id,$uid=''){
        !empty($id) &&  S($this->sp_user_address_detail_cache_key.$id,null);
        !empty($uid) &&  S($this->sp_user_address_list_cache_key.$uid,null);
    }
}
?>